using Aliyun.Acs.Core.Logging;
using JNPF.Basics.Controller.WeChat;
using JNPF.Basics.Logic;
using JNPF.Basics.Logic.Common.Login;
using JNPF.Basics.Models;
using JNPF.Utils;
using JNPF.Utils.Controller;
using JNPF.Utils.Extensions;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Polly;
using Senparc.Weixin.Tencent;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using wxLib.QRCode;
using WxLib.Sns;

namespace JNPF.Basics.Controller
{
    /// <summary>
    /// 公众号
    /// </summary>
    [Route("api/Jiushi/[Controller]")]
    public class zzhuserController : BaseApiController
    {
        private jiushiZzhuserBll jiushiZzhuserService = new jiushiZzhuserBll();
        private BillRuleBll billRuleService = new BillRuleBll();
        private DataInterfaceBll dataInterfaceBll = new DataInterfaceBll();
        private UserBll userBll = new UserBll();
        private OrganizeBll organizeBll = new OrganizeBll();

        /// <summary>
        ///验证小程序信息
        /// </summary>
        /// <param name="authenticationRequest">authenticationRequest</param>
        /// <returns>返回对象Json</returns>
        [HttpPost("XcxAuthentication")]
        [AllowAnonymous]
        public async Task<ResponseResult> XcxAuthentication(AuthenticationRequest authenticationRequest)
        {
            var watch = CommonHelper.TimerStart();

            //调试记录日志的方法
            LogFactory.GetLogger().Debug("XcxAuthentication" + authenticationRequest.ToJson());



            Utils.Code2SessionResponse code2SessionResponse = await WeChatHttpHelper.GetJsCode2SessionAsync(authenticationRequest.loginCode);
            if (string.IsNullOrEmpty(code2SessionResponse.openid) || string.IsNullOrEmpty(code2SessionResponse.unionid))
            {
                return Error("未获取到用户信息" + code2SessionResponse.ToJson());

            }
            jiushiZzhuserEntity jiushiZzhuserEntity = await jiushiZzhuserService.GetInfoByXcxOpenId(code2SessionResponse.openid);
            if (jiushiZzhuserEntity == null || string.IsNullOrEmpty(jiushiZzhuserEntity.Id))
            {
                //查询下 公众号有么有关注，关注了的话 往里面塞 小程序 

                jiushiZzhuserEntity = await jiushiZzhuserService.GetInfoByuuid(code2SessionResponse.unionid);

                if (jiushiZzhuserEntity == null || string.IsNullOrEmpty(jiushiZzhuserEntity.Id))
                {
                    jiushiZzhuserEntity = new jiushiZzhuserEntity();
                    jiushiZzhuserEntity.XcxOpenId = code2SessionResponse.openid;
                    jiushiZzhuserEntity.Uuid = code2SessionResponse.unionid;

                    await jiushiZzhuserService.Create(jiushiZzhuserEntity);
                }
                else
                {
                    jiushiZzhuserEntity.XcxOpenId = code2SessionResponse.openid;

                    await jiushiZzhuserService.Update(jiushiZzhuserEntity.Id, jiushiZzhuserEntity);
                }

            }

            return Success(code2SessionResponse);

        }



        /// <summary>
        /// 企代办CRM请求--对接公众号开发
        /// </summary>
        /// <returns></returns>
        [HttpGet("wx")]
        [AllowAnonymous]
        public ActionResult CheckSignature(string sigNature = "a97b77ee4e42928ff924da494e1ab6ab16508a37", string timestamp = "1541574990", string nonce = "1736430880", string echoStr = "7572137059867136462")
        {
            var content =
                    string.Format("SigNature:{0}\nTimestamp:{1}\nNonce:{2}\nEchoStr:{3}",
                                  sigNature, timestamp, nonce, echoStr);
            LogFactory.GetLogger().Error("CheckSignature" + content);

            var str = string.Empty;
            var token = "qidaiban2020";
            var parameter = new List<string> { token, timestamp, nonce };
            parameter.Sort();
            var parameterStr = parameter[0] + parameter[1] + parameter[2];
            var tempStr = WxHelp.GetSHA1(parameterStr).Replace("-", "").ToLower();
            if (tempStr == sigNature && !string.IsNullOrEmpty(echoStr))     //根据微信的验证规则做判断
                return GetReturn(echoStr);
            return GetReturn("error");
        }

        WeChatHttpHelper weChatHttpHelper = new WeChatHttpHelper();

        private static readonly Regex ToUserNameReg = new Regex(@"(?<=<ToUserName><!\[CDATA\[).*?(?=\]\]></ToUserName>)", RegexOptions.Compiled);
        private static readonly Regex FromUserNameReg = new Regex(@"(?<=<FromUserName><!\[CDATA\[).*?(?=\]\]></FromUserName>)", RegexOptions.Compiled);
        private static readonly Regex CreateTimeReg = new Regex(@"(?<=<CreateTime>)\d*?(?=</CreateTime>)", RegexOptions.Compiled);
        private static readonly Regex MsgTypeReg = new Regex(@"(?<=<MsgType><!\[CDATA\[).*?(?=\]\]></MsgType>)", RegexOptions.Compiled);
        private static readonly Regex ContentReg = new Regex(@"(?<=<Content><!\[CDATA\[).*?(?=\]\]></Content>)", RegexOptions.Compiled);
        private static readonly Regex MsgIdReg = new Regex(@"(?<=<MsgId>)\d*?(?=</MsgId>)", RegexOptions.Compiled);
        private static readonly Regex EventReg = new Regex(@"(?<=<Event><!\[CDATA\[).*?(?=\]\]></Event>)", RegexOptions.Compiled);
        private static readonly Regex EventKeyReg = new Regex(@"(?<=<EventKey><!\[CDATA\[).*?(?=\]\]></EventKey>)", RegexOptions.Compiled);

        /// <summary>
        /// 企代办CRM请求--对接公众号开发
        /// </summary>
        /// <returns></returns>
        [HttpPost("wx")]
        [AllowAnonymous]
        public async Task<ActionResult> GetApi()
        {
            try
            {


                Stream stream = HttpContext.Request.Body;
                byte[] buffer = new byte[HttpContext.Request.ContentLength.Value];


                await stream.ReadAsync(buffer, 0, buffer.Length);
                string message = Encoding.UTF8.GetString(buffer);


                LogFactory.GetLogger().Error("GetApi" + message);

                var toUserName = WxHelp.GetItemValue(message, ToUserNameReg);
                var fromUserName = WxHelp.GetItemValue(message, FromUserNameReg);
                var createTime = WxHelp.GetItemValue(message, CreateTimeReg);
                var msgType = WxHelp.GetItemValue(message, MsgTypeReg);
                var content = WxHelp.GetItemValue(message, ContentReg);
                var msgId = WxHelp.GetItemValue(message, MsgIdReg);
                var eventStr = WxHelp.GetItemValue(message, EventReg);
                var eventKey = WxHelp.GetItemValue(message, EventKeyReg);

                var userInfoResponse = WeChatHttpHelper.UserInfo(fromUserName);

                jiushiZzhuserEntity jiushiZzhuserEntity = await jiushiZzhuserService.GetInfoByOpenid(fromUserName);


                if (jiushiZzhuserEntity == null || string.IsNullOrEmpty(jiushiZzhuserEntity.Id))
                {
                    //查询下 公众号有么有关注，关注了的话 往里面塞 小程序 

                    jiushiZzhuserEntity = await jiushiZzhuserService.GetInfoByuuid(userInfoResponse.unionid);

                    if (jiushiZzhuserEntity == null || string.IsNullOrEmpty(jiushiZzhuserEntity.Id))
                    {
                        jiushiZzhuserEntity = new jiushiZzhuserEntity();
                        jiushiZzhuserEntity.OpenId = userInfoResponse.openid;
                        jiushiZzhuserEntity.Uuid = userInfoResponse.unionid;

                        await jiushiZzhuserService.Create(jiushiZzhuserEntity);
                    }
                    else
                    {
                        jiushiZzhuserEntity.OpenId = userInfoResponse.openid;

                        await jiushiZzhuserService.Update(jiushiZzhuserEntity.Id, jiushiZzhuserEntity);
                    }

                }
                switch (msgType)
                {
                    //反馈信息
                    case "text":
                        {
                            return GetReturn(WxHelp.GetSendMessage(fromUserName, "欢迎来电：137-7181-0219(微信同号)。", toUserName));
                        }
                    case "event":
                        {
                            //关注或者重复关注
                            if (eventStr == "subscribe" || eventStr == "SCAN" || eventStr == "unsubscribe")// 关注事件
                            {
                                jiushiZzhuserEntity.IsFollow = 1;
                                if (eventStr == "unsubscribe") //取消关注
                                {
                                    jiushiZzhuserEntity.IsFollow = -1;
                                    jiushiZzhuserEntity.CancelScribeTime = DateTime.Now;
                                }
                                await jiushiZzhuserService.Update(jiushiZzhuserEntity.Id, jiushiZzhuserEntity);

                                return GetReturn(WxHelp.GetSendMessage(fromUserName, "感谢关注。", toUserName));

                            }
                            //点击事件
                            if (eventStr == "CLICK")
                            {
                                //人工客服
                                if (eventKey == "server")
                                {
                                    return GetReturn(WxHelp.GetSendMessage(fromUserName, "欢迎来电：137-7181-0219(微信同号)。", toUserName));

                                }
                            }
                            return GetReturn(WxHelp.GetSendMessage(fromUserName, "/微笑", toUserName));

                        }
                    default:
                        return GetReturn(WxHelp.GetSendMessage(fromUserName, "/微笑", toUserName));
                }
            }
            catch (Exception ex)
            {
                LogFactory.GetLogger().Error("GetApi" + ex.ToString());
            }

            return GetReturn("");
        }

        /// <summary>
        /// 清空token
        /// </summary>
        /// <returns></returns>
        [HttpPost("RemoveToken")]
        [AllowAnonymous]
        public ActionResult RemoveToken()
        {

            //先清空token,再走一遍
            WeChatHttpHelper.RemoveToken();

            return GetReturn("");
        }









    }


}